<template>
  <div class="upload-container">
    <div class="upload-header">
      <button class="upload-btn" @click="triggerUpload">
        <i class="icon">📤</i>
        上传图片
      </button>
      <select v-model="selectedCategory" class="category-select">
        <option value="">选择分类...</option>
        <option v-for="category in categories" 
                :key="category.id" 
                :value="category.id">
          {{ category.name }}
        </option>
      </select>
    </div>

    <div class="image-list">
      <div v-for="image in images" 
           :key="image.id" 
           class="image-item">
        <img :src="`/uploads/${image.filename}`" 
             :alt="image.filename">
        <div class="image-info">
          <span class="filename">{{ image.filename }}</span>
          <span class="category">
            分类: {{ getCategoryName(image.category_id) }}
          </span>
        </div>
      </div>
    </div>

    <input type="file"
           ref="fileInput"
           style="display: none"
           accept="image/*"
           multiple
           @change="handleFileSelect">
           
    <div class="export-section">
      <button class="export-btn" @click="exportDataset">
        <i class="icon">📦</i>
        导出数据集
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'

const fileInput = ref(null)
const selectedCategory = ref('')
const categories = ref([])
const images = ref([])

// 触发文件选择
const triggerUpload = () => {
  fileInput.value.click()
}

// 处理文件选择
const handleFileSelect = async (event) => {
  const files = event.target.files
  if (!files.length) return

  for (const file of files) {
    const formData = new FormData()
    formData.append('file', file)
    if (selectedCategory.value) {
      formData.append('category_id', selectedCategory.value)
    }

    try {
      const response = await axios.post('/api/upload', formData, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
          'Content-Type': 'multipart/form-data'
        }
      })
      images.value.unshift(response.data)
    } catch (err) {
      console.error('上传失败:', err)
      alert('上传失败')
    }
  }
  
  // 清除文件选择
  event.target.value = ''
}

// 获取分类名称
const getCategoryName = (categoryId) => {
  const category = categories.value.find(c => c.id === categoryId)
  return category ? category.name : '未分类'
}

// 导出数据集
const exportDataset = async () => {
  try {
    const response = await axios.get('/api/export', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      },
      responseType: 'blob'
    })
    
    // 创建下载链接
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', 'dataset.zip')
    document.body.appendChild(link)
    link.click()
    link.remove()
  } catch (err) {
    console.error('导出失败:', err)
    alert('导出失败')
  }
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const response = await axios.get('/api/categories', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    categories.value = response.data
  } catch (err) {
    console.error('获取分类失败:', err)
  }
}

// 获取图片列表
const fetchImages = async () => {
  try {
    const response = await axios.get('/api/images', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    images.value = response.data
  } catch (err) {
    console.error('获取图片失败:', err)
  }
}

onMounted(() => {
  fetchCategories()
  fetchImages()
})
</script>

<style scoped>
.upload-container {
  padding: 20px;
}

.upload-header {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.upload-btn,
.export-btn {
  padding: 8px 16px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
}

.category-select {
  padding: 8px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  min-width: 150px;
}

.image-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.image-item {
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  overflow: hidden;
}

.image-item img {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.image-info {
  padding: 8px;
}

.filename {
  display: block;
  font-size: 14px;
  color: #666;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.category {
  display: block;
  font-size: 12px;
  color: #999;
}

.export-section {
  margin-top: 20px;
  text-align: right;
}
</style> 